﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;
using KPIS.GERP.ESS.APP.App_UI.Commons;
using KPIS.GERP.ESS.APP.SysApprovalService;
using KPIS.GERP.ESS.DAL;
using KPIS.GERP.ESS.MODEL;
using Telerik.Web.UI;

namespace KPIS.GERP.ESS.APP.App_UI.Forms
{
    public partial class RequestAbsencesNew : System.Web.UI.Page
    {
        private D_HrmEmployees employeesDal = new D_HrmEmployees();
        private D_Absence absenceDal = new D_Absence(); 
        private SysApprovalService.SysApprovalService approvalService = new SysApprovalService.SysApprovalService();
        List<VM_Absence> absencesAll = new List<VM_Absence>();
        public Main main = new Main();

        protected void Page_Load(object sender, EventArgs e)
        {
            /* */
            if (!Page.IsPostBack)
            {
                if (UiMode == UiModeEnum.Index)
                { 
                    LoadYearDropdownlist();
                    LoadAbsenceTypeDropdownList();
                    LoadGridAbsence();
                    radGrdAbsence.DataBind();
                    pnlIndex.Visible = true;
                }else if(UiMode == UiModeEnum.CheckRule)
                {
                    int status;
                    CheckAbsenceRuleResultVM reqResult;
                    var response = RequestAbsencesNew1.CheckRuleMessage(Request["emp_seq"],
                                                        Request["currentAbsenceSeq"],
                                                        Request["absence_type_seq"],
                                                        Request["start_date"],
                                                        Request["end_date"],
                                                        Request["created_by"],
                                                        Request["start_time"],
                                                        Request["end_time"]);
                    response.Remarks = response.Remarks.Replace("\"", "'");
                    
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    string result = js.Serialize(response);

                    Response.Clear();
                    Response.ContentType = "application/json; charset=utf-8";
                    Response.Write(result);
                    Response.End();
                }
                else
                {
                    pnlIndex.Visible = false;
                    RequestAbsencesNew1.Visible = true;
                    M_HrmAbsenceNew model = null;
                    if(AbsenceSeq.HasValue)
                    {
                        model = absenceDal.AbsenceNewList(AbsenceSeq, true).FirstOrDefault();
                    }

                    if(model == null)
                    {
                        model = new M_HrmAbsenceNew
                            {
                                emp_seq = SsMng.EmpSeqI,
                                start_date = DateTime.Now,
                                end_date = DateTime.Now,
                                start_time = "M",
                                end_time = "A",
                                _emp_name = employeesDal.GetEmployeeFullName(main.ConvertNullInt(SsMng.EmpSeqI)??0),
                                bgm_year = main.GetSystemControls().default_bgm_year.Value,
                                request_title = "คำขอลาของ " + SsMng.UserName
                            };
                    }
                    RequestAbsencesNew1.LoadData(UiMode, model);
                }
            }
        }

        private void LoadAbsenceTypeDropdownList()
        {
            var absenceTypeAll = absenceDal.AbsenceTypeList(); 

            ddlFilterAbsenceType.Items.Add(new ListItem("ทั้งหมด", ""));
            foreach(var absenceType in absenceTypeAll)
            {
                ddlFilterAbsenceType.Items.Add(new ListItem(absenceType.absence_type_name, absenceType.absence_type_seq.ToString()));
            }
             
            ddlFilterAbsenceType.SelectedIndex = 0;
             
        }

        protected void btnCancelEdit_Click(object sender, EventArgs e)
        {
            Session["ReqResponse"] = null;
            UpdateUi(RequestAbsencesNew1.Model.absence_seq.ToString());
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            Session["ReqResponse"] = null;
            var item = RequestAbsencesNew1.Model;

            if (item.absence_seq > 0)
            {
                absenceDal.DeleteHrmPsAbsence(item.absence_seq, SsMng.EmpSeqI);
            }
            Response.Redirect("RequestAbsencesNew.aspx");
        }

        protected void radGrdAbsence_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            LoadGridAbsence();
        }

        protected void btnIndex_Click(object sender, EventArgs e)
        {
            Session["ReqResponse"] = null;
            Response.Redirect("RequestAbsencesNew.aspx");
        }

        #region

        private void LoadYearDropdownlist()
        {
            //var absenceAll = absenceDal.AbsenceList(null, null, SsMng.EmpSeqI, null);
            int currentYear = new ThaiBuddhistCalendar().GetYear(DateTime.Now) + (DateTime.Now.Month < 10 ? 0 : 1);
            //int maxYear = currentYear, minYear = currentYear;
            //maxYear = absenceAll.Select(v => Convert.ToInt32(v.ปี)).Concat(new[]{maxYear}).Max();
            //minYear = absenceAll.Select(v => Convert.ToInt32(v.ปี)).Concat(new[]{maxYear}).Min(); 
            //for(int i = minYear ; i  <= maxYear; i++)
            //{
            //    ddlFilterYear.Items.Add(new ListItem(i.ToString(), i.ToString()){Selected = i == currentYear});
            //} 

            ddlFilterYear.SelectedValue = currentYear.ToString();
        }

        public void LoadGridAbsence()
        {
            string selectedYear = ddlFilterYear.SelectedValue,
                   selectedRecordStatus = ddlFilterRecordStatus.SelectedValue,
                   selectedAbsenceTypeSeq = ddlFilterAbsenceType.SelectedValue;
            bool includeDeleteled = selectedRecordStatus == "ถูกลบ";

            List<VM_Absence> ds1 = absenceDal.AbsenceList(null, null, SsMng.EmpSeqI, null, includeDeleteled).Where(d => d.ปี == selectedYear).ToList(),
                             ds2 = new List<VM_Absence>(),
                             ds3 = new List<VM_Absence>();

            
            if(!string.IsNullOrEmpty(selectedRecordStatus))
            {
                ds2.AddRange(ds1.Where(d => d.สถานะ == selectedRecordStatus));
            } else
            {
                ds2.AddRange(ds1);
            }

            if(!string.IsNullOrEmpty(selectedAbsenceTypeSeq))
            {
                ds3.AddRange(ds2.Where(d => d.เลขที่ประเภทคำขอ == selectedAbsenceTypeSeq));
            } else
            {
                ds3.AddRange(ds2);
            }

            radGrdAbsence.DataSource = ds3;
            try
            {
                radGrdAbsence.DataBind();
            } catch (System.Exception ex)
            {
                // Sometime Error On Need Datasource Of RadGrid
            }
        }

        private void UpdateUi(string absenceSeq, bool isEdit = false)
        {
            if (!String.IsNullOrEmpty(absenceSeq))
            {
                var model = absenceDal.AbsenceNewList(Convert.ToInt32(absenceSeq)).FirstOrDefault();
                if (model != null)
                {
                    RequestAbsencesNew1.Model = model;
                }
                else
                {
                    Response.Redirect("RequestAbsencesNew.aspx");
                }

                Page.DataBind();
            }
        }

        #endregion

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            GoToEdit(RequestAbsencesNew1.Model.absence_seq);
        }

        protected void radGrdAbsence_SelectedIndexChanged(object sender, EventArgs e)
        {
            string absenceSeqStr = radGrdAbsence.SelectedItems.Count > 0 && (radGrdAbsence.SelectedItems[0] as GridDataItem) != null
                                       ? (radGrdAbsence.SelectedItems[0] as GridDataItem)["เลขที่"].Text
                                       : String.Empty;

            int absenceSeq = Convert.ToInt32(absenceSeqStr);

            GoToDetail(absenceSeq);
        }

        protected void btnIndex_Click1(object sender, EventArgs e)
        {
            GoToIndex();
        }

        protected void lbtCreate_Click(object sender, EventArgs e)
        {
            GoToCreate();
        }

        protected void lbtlbtDefailt_Click(object sender, EventArgs e)
        {

        }

        protected void lbtDefailt_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
        { 
            int? absenceSeq = main.ConvertNullInt(e.CommandArgument);
            if (absenceSeq.HasValue)
            {
                GoToDetail(absenceSeq.Value);
            }
        }

        protected void ddlFilterRecordStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadGridAbsence();
        }

        protected void ddlFilterYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadGridAbsence();
        }

        protected void ddlFilterAbsenceType_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadGridAbsence();
        } 


        public int? AbsenceSeq
        {
            get { return main.ConvertNullInt(main.Get("AbsenceSeq")); }
        }

        public UiModeEnum UiMode
        {
            get
            {
                if (main.IsSameValueGet("do", UiModeEnum.Create)) return UiModeEnum.Create;
                if (main.IsSameValueGet("do", UiModeEnum.Edit)) return UiModeEnum.Edit;
                if (main.IsSameValueGet("do", UiModeEnum.Detail)) return UiModeEnum.Detail;
                if (main.IsSameValueGet("do", UiModeEnum.CheckRule)) return UiModeEnum.CheckRule;
                return UiModeEnum.Index;
            }
        }

        public void GoToIndex()
        {
            Response.Redirect("RequestAbsencesNew.aspx");
        }

        public void GoToCreate()
        {
            Response.Redirect("RequestAbsencesNew.aspx?do=Create");
        }

        public void GoToEdit(int absenceSeq)
        {
            Response.Redirect("RequestAbsencesNew.aspx?AbsenceSeq=" + absenceSeq + "&do=Edit");
        }

        public void GoToDetail(int absenceSeq)
        {
            Response.Redirect("RequestAbsencesNew.aspx?AbsenceSeq=" + absenceSeq + "&do=Detail");
        }
    }



    public enum UiModeEnum
    {
        Create,
        Edit,
        Index,
        Detail,
        CheckRule
    }
}